<template>
  <view class="container">
    <view class="login-box">
      <text class="title">登录</text>
      <input v-model="username" placeholder="请输入用户名" class="input" />
      <input v-model="password" type="password" placeholder="请输入密码" class="input" />
      <button @click="login" class="login-button">登录</button>
      <text class="error-message" v-if="errorMessage">{{ errorMessage }}</text>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js';

export default {
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    };
  },
  methods: {
    login() {
      if (this.username === '' || this.password === '') {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }
	  request({
		  url: '/users/login',
		  method: 'post',
		  data: {username: this.username, password: this.password}
		}).then(response => {
		    if (response.code === 200 && response.data.token) {
		            // 如果登录成功，将 token 存储到 localStorage
		            const token = response.data.token;
		            localStorage.setItem('token', token);
		            // 可以在这里添加更多的登录成功处理逻辑，比如跳转到主页
		            // 登录成功后，可以跳转到主页
		            uni.navigateTo({
		              url: '/pages/index/index'
		            });
		  } else {
			// 如果登录失败，显示错误信息
			console.error('登录失败:', response.msg);
			this.errorMessage = response.msg || '未知错误'; 
			
		  }
		}).catch(error => {
		  console.error('请求失败:', error);
		});
  
    }
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  width: 300px;
  padding: 20px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  text-align: center;
  margin-bottom: 20px;
}

.input {
  width: 100%;
  padding: 10px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.login-button {
  width: 100%;
  padding: 10px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
    display: block; /* 确保元素是显示的 */

}
</style>
